<?php

namespace App\Console;

use App\Http\Service\RedisService;
use App\Utils\MyRedis;
use Illuminate\Console\Command;
use Workerman\Lib\Timer;
use Workerman\Worker;

class WorkmanTimer extends Command
{
    protected $signature = 'workerman:timer {action} {--daemon}';
    protected $description = 'Start Workerman timer service';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        global $argv;
        if (!in_array($action = $this->argument('action'), ['start', 'stop', 'restart'])) {
            $this->error('Error Arguments');
            exit;
        }
        $argv[0] = 'workerman:timer';
        $argv[1] = $action;
        $argv[2] = $this->option('daemon') ? '-d' : '';//该参数是以daemon（守护进程）方式启动
        $this->start();
    }

    public function start()
    {
        $task = new Worker();
        $task->count = 1;
        $task->onWorkerStart = function (Worker $task) {
            // 每隔10秒执行一次watchdog
            Timer::add(10, function () {
                // 重置分布式锁的ttl
                $myReids = MyRedis::getInstance();
                $keys = $myReids->distributedExReSet(15);
                // 向客户端发送一下消息
                if (!empty($keys)) {
                    $redisService = new RedisService();
                    $uids = $redisService->distributedLockWatchDogSendMsg($keys);
                    $this->info('watchdog 重置分布式锁 uid:' . implode(',', $uids));
                }
                //特殊处理一下demo 向前端发送消息
                $this->info('watchdog 重置分布式锁, keys:' . implode(',', $keys));
            });
        };
        // 设置一下pid避免和gatewayworker冲突
        Worker::$pidFile = base_path() . '/storage/timer.pid';
        // 启动Workerman
        Worker::runAll();
    }
}
